﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraRichEdit.Model;
using TheHeGeoDao;

namespace TheHeGeoManager.Uc
{
    public partial class UcWarning : UserControl
    {
        private Double time0 = 60;
        private Double time1 = 300;
        private Double time2 = 600;
        private Double time4 = 1200;
        private Double time5 = 3600;
        private int intervalCheck = 10000;
        private bool isCheck = false;
        public UcWarning()
        {
            InitializeComponent();
        }

        public void WarningRun()
        {
            intervalCheck = Convert.ToInt32(txtCheckRequest.Text) * 1000;

            txtNumbSuccessPkg.Text = "";
            if (isCheck == false)
            {
                isCheck = true;
                Thread t = new Thread(SensorMonitoring);
                t.Start();
            }
            btnStart.Enabled = false;
        }
        private void btnStart_Click(object sender, EventArgs e)
        {

            intervalCheck = Convert.ToInt32(txtCheckRequest.Text) * 1000;
          
            txtNumbSuccessPkg.Text = "";
            if (isCheck == false)
            {
                isCheck = true;
                Thread t = new Thread(SensorMonitoring);
                t.Start();
            }
            btnStart.Enabled = false;
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                isCheck = false;
            }
            else
            {
                isCheck = false;
            }

            btnStart.Enabled = true;
        }

        public void SensorMonitoring()
        {
            while (true)
            {
                CheckSensorRunning();
                Thread.Sleep(intervalCheck);
            }
        }
        public void CheckSensorRunning()
        {
            try
            {
                var listSensor = (from s in DaoHelper.Entities.Sensors
                                  join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                                  join p in DaoHelper.Entities.DuAns on t.MaDuAn equals p.MaDuAn
                                  join us in DaoHelper.Entities.NguoiSuDungs on p.UserName equals us.UserName
                                  where (s.TrangThaiTest == 1)
                                  select new
                                  {
                                      s.MaSensor,
                                      s.TenSensor,
                                      p.MaDuAn,
                                      p.TenDuAn,
                                      t.TgLayMau,
                                      us.Email

                                  }).ToList();
                if (listSensor.Count == 0)
                    return;
                string message = txtNumbSuccessPkg.Text;
                foreach (var sensor in listSensor)
                {
                    var value = (from s in DaoHelper.Entities.SensorLatestValues
                                 where (s.MaDuAn == sensor.MaDuAn && s.MaSensor == sensor.MaSensor)
                                 select new
                                 {
                                     s.MaDuAn,
                                     s.MaSensor,
                                     s.GiaTri,
                                     s.ThoiGianDo,
                                     s.ThoiGianNhan

                                 }).FirstOrDefault();
                    if (value != null)
                    {
                        Double time = 0;
                        Double timeNoSend = 0;

                        if (sensor.TgLayMau <= time0)
                        {
                            time = sensor.TgLayMau * 10;
                        }
                        else if (sensor.TgLayMau < time2)
                        {
                            time = sensor.TgLayMau * 6;
                        }
                        else
                        {
                            time = sensor.TgLayMau * 2;
                        }
                        timeNoSend = (DateTime.Now - value.ThoiGianNhan).TotalSeconds;
                        if (timeNoSend > time)
                        {
                           var f = (timeNoSend/3600);
                            var f1 = Math.Round((Decimal) f, 3, MidpointRounding.AwayFromZero);
                            message += "--------------------------------------------------------------------------------------\r\n";
                            message += DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss   ") + "Sensor: " + sensor.TenSensor + " thuộc dự án: " + sensor.TenDuAn + " không gửi dữ liệu trong " + f1 + " giờ\r\n";
                            if (InvokeRequired)
                            {
                                txtNumbSuccessPkg.Invoke(new Action(() => txtNumbSuccessPkg.Text = message));
                            }
                            else
                            {
                                txtNumbSuccessPkg.Text = message;
                            }
                        }

                        if (timeNoSend > time * 2)
                        {
                           var f = (timeNoSend/3600);
                            var f1 = Math.Round((Decimal) f, 3, MidpointRounding.AwayFromZero);
                            var list = new List<string> { sensor.Email };
                            var message1 = "Sensor: " + sensor.TenSensor + " thuộc dự án: " + sensor.TenDuAn + " không gửi dữ liệu trong " + f1 + " giờ";
                            SendEmail(list, "thehegeo2014@gmail.com ", "TheHeGeo cảnh báo sensor không gửi dữ liệu!", message1, "smtp.gmail.com", 587, "thehegeo2014", "12345@trewq");
                        }

                    }
                }
            }
            catch (Exception ex)
            {
              
            }
           
        }

        public static void SendEmail(List<string> to,
                                     string form, string subj,
                                     string body, string host, int port,
                                     string userName, string passw)
        {
            try
            {
                var mail = new MailMessage();
                foreach (var t in to)
                {
                    mail.To.Add(t);
                }
                mail.From = new MailAddress(form);
                mail.Subject = subj;
                mail.Body = body;
                mail.IsBodyHtml = true;

                var smtp = new SmtpClient();
                smtp.Host = host; //Or Your SMTP Server Address,"smtp.gmail.com"
                smtp.Credentials = new NetworkCredential(userName, passw); //Or your Smtp Email ID and Password
                smtp.EnableSsl = true;
                smtp.Port = port; //587; //If not work, you can use 25 here....
                smtp.Send(mail);
            }
            catch (Exception)
            {

            }
        }
    }
}
